package org.van.blog.controller.admin;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.PageInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.van.blog.api.QiNiuCloudService;
import org.van.blog.constant.ErrorConstant;
import org.van.blog.constant.LogActions;
import org.van.blog.constant.Types;
import org.van.blog.constant.WebConst;
import org.van.blog.controller.BaseController;
import org.van.blog.dto.AttAchDto;
import org.van.blog.exception.BusinessException;
import org.van.blog.model.AttAchDomain;
import org.van.blog.model.UserDomain;
import org.van.blog.service.attach.AttAchService;
import org.van.blog.service.log.LogService;
import org.van.blog.utils.APIResponse;
import org.van.blog.utils.Commons;
import org.van.blog.utils.TaleUtils;

@Controller
@RequestMapping("admin/attach")
public class AttachController extends BaseController {

    public static final String CLASSPATH = TaleUtils.getUploadFilePath();

    @Autowired
    private AttAchService attAchService;

    @Autowired
    private LogService logService;

    @GetMapping(value = "")
    public String index(
            HttpServletRequest request,

            @RequestParam(name = "page", required = false, defaultValue = "1") int page,

            @RequestParam(name = "limit", required = false, defaultValue = "12") int limit) {
        PageInfo<AttAchDto> atts = attAchService.getAtts(page, limit);
        request.setAttribute("attachs", atts);
        request.setAttribute(Types.ATTACH_URL.getType(),
                Commons.site_option(Types.ATTACH_URL.getType(), Commons.site_url()));
        request.setAttribute("max_file_size", WebConst.MAX_FILE_SIZE / 1024);
        return "admin/attach";
    }

    @PostMapping(value = "/uploadfile")
    public void fileUploadToTencentCloud(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(name = "editormd-image-file", required = true) MultipartFile file) {

    }

    @PostMapping(value = "upload")
    @ResponseBody
    public APIResponse<?> filesUploadToCloud(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(name = "file", required = true) MultipartFile[] files) {
        try {
            request.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "text/html");
            
            for (MultipartFile file : files) {
                String fileName = TaleUtils.getFileKey(file.getOriginalFilename().replaceFirst("/", ""));
                QiNiuCloudService.upload(file, fileName);
                AttAchDomain attAchDomain = new AttAchDomain();
                HttpSession session = request.getSession();
                UserDomain sessionUser = (UserDomain) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
                attAchDomain.setAuthorId(sessionUser.getUid());
                attAchDomain.setFtype(
                        TaleUtils.isImage(file.getInputStream()) ? Types.IMAGE.getType() : Types.FILE.getType());
                attAchDomain.setFname(fileName);
                attAchDomain.setFkey(QiNiuCloudService.QINIU_UPLOAD_SITE + fileName);
                attAchService.addAttAch(attAchDomain);
            }
            return APIResponse.success();

        } catch (IOException e) {
            e.printStackTrace();
            throw BusinessException.withErrorCode(ErrorConstant.Att.ADD_NEW_ATT_FAIL)
                    .withErrorMessageArguments(e.getMessage());
        }

    }

    @PostMapping(value = "/delete")
    @ResponseBody
    public APIResponse<?> deleteFileInfo(
            HttpServletRequest request,
            @RequestParam(name = "id", required = true) Integer id) {
        try {
            AttAchDto attach = attAchService.getAttAchById(id);
            if (null == attach)
                throw BusinessException.withErrorCode(ErrorConstant.Att.DELETE_ATT_FAIL + ": File not exist!");
            attAchService.deleteAttAch(id);
            logService.addLog(LogActions.DEL_ATTACH.getAction(), this.user(request).getUsername() + "User",
                    request.getRemoteAddr(), this.getUid(request));
            return APIResponse.success();
        } catch (Exception e) {
            e.printStackTrace();
            throw BusinessException.withErrorCode(e.getMessage());
        }
    }

}
